<?php
defined('SYS_RUN') or exit();

class Session
{
    /**
     * DB connection object
     * @var object
     */
    private $connection;

    public function __construct() {
        $this->connection = Lib::get('connector');

        session_set_save_handler(
            array($this, 'open'),
            array($this, 'close'),
            array($this, 'read'),
            array($this, 'write'),
            array($this, 'destroy'),
            array($this, 'gc')
        );
    }

    public function init() {
        session_start();
    }

    public function set($name, $value) {
        $_SESSION[$name] = serialize($value);
    }

    public function get($name) {
        if(isset($_SESSION[$name]))
            return unserialize($_SESSION[$name]);
        else return false;
    }

    public function open() {
        return true;
    }

    public function close() {
        return true;
    }

    public function read($sessionId) {
        $response = $this->connection->send('session', 'read', array(
            'sessionId' => $sessionId
        ));
        return $response['data'];
    }

    public function write($sessionId, $data) {
        $this->connection->send('session', 'write', array(
            'sessionId'     => $sessionId,
            'sessionData'   => $data
        ));
        return true;
    }

    public function destroy($sessionId) {
        $this->connection->send('session', 'destroy', array(
            'sessionId'     => $sessionId
        ));
        return true;
    }

    public function gc($maxLifeTime) {
//        $currentTime = time();
//        $this->db->remove(array(
//            'timestamp' => array(
//                    '$gt'   => $maxLifeTime + $currentTime
//            )
//        ));
        return true;
    }
}